const fs = require('fs');
const path = require('path');
const createWorker = require("./woker_thread");
let worker = null;
let changeState = false;

/**
 * 监视指定地址下文件变化的函数
 * @param {string} directory 监视的地址，可以是相对路径或绝对路径
 */
function watchDir(directory) {
    // 处理相对路径和绝对路径
    const resolvedDir = path.resolve(directory);

    console.log('watching... in resolvedDir:',resolvedDir)

    return new Promise((resolve, reject) => {
        const watcher = fs.watch(resolvedDir, { recursive: true }, (eventType, filename) => {
            if (filename) {
                console.log(`File ${filename} changed`);
                const filePath = path.join(resolvedDir, filename);
                resolve({ eventType, filePath });
            }
        });

        watcher.on('error', (error) => {
            reject(error);
        });
    });
}


/**
 * 监视指定地址下文件变化的函数
 * @param {string} directory 监视的地址，可以是相对路径或绝对路径
 * @param {function} callback 回调函数，当文件变化时调用，参数为null
 */
function watchDirCallBack(directory, callback) {
    // 处理相对路径和绝对路径
    const resolvedDir = path.resolve(directory);

    console.log('watching... in resolvedDir:',resolvedDir)

    fs.watch(directory, { recursive: true }, (eventType, filename) => {
        if (filename) {
            console.log(`File ${filename} changed`);
            callback(eventType, filename);
        }
    });
}


/**
 * 监视指定地址下文件变化的函数,超时自动回调
 * @param {string} dirPath 监视的地址，可以是相对路径或绝对路径
 * @param {number} timeout 超时时间，单位为毫秒
 * @param {function} callback 回调函数，当文件变化时调用，参数为null
 */
function watchFileChange(dirPath, timeout, callback) {
    // 将地址转为绝对路径
    dirPath = path.resolve(dirPath);

    // 创建一个文件变化监视器
    const watcher = fs.watch(dirPath, { recursive: true }, (eventType, filename) => {
        // 只处理修改或添加事件
        if (eventType === 'change' || eventType === 'rename') {
            // 如果有文件变化，解除监视器并调用回调函数
            changeState = true;
            // watcher.close();
            // callback()
        }
    });

    // 设置超时定时器，超时后解除监视器并调用回调函数
    setTimeout(() => {
        watcher.close();

        // 创建一个子线程并执行指定文件
        if (changeState){
            // console.log('eventType 触发')
            if(worker) worker.terminate();
            //更改线程执行的功能 @todo

            //①create_file_random
            // let funPath =  path.resolve('./build-tools/create_file_random.js')
            // console.log('funPath',funPath)
            // worker = createWorker(funPath, {}, './test.txt', 1024, 'text');

            //②create_file
            let funPath =  path.resolve('./build-tools/create_file.js')
            worker = createWorker(funPath, {}, );

            callback()
            changeState = false
        }
    }, timeout);
}

// 使用示例
// watchFileChange('./test', 5000, (err) => {
//     if (err) {
//         console.error(err);
//     } else {
//         console.log('文件变化了！');
//     }
// });


module.exports = {
    watchDir,
    watchDirCallBack,
    watchFileChange
};
